/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.jcdev.coolrss.model.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import net.jcdev.coolrss.model.dao.exceptions.IllegalOrphanException;
import net.jcdev.coolrss.model.dao.exceptions.NonexistentEntityException;
import net.jcdev.coolrss.model.dao.exceptions.PreexistingEntityException;
import net.jcdev.coolrss.model.entity.Feed;
import java.util.ArrayList;
import java.util.List;
import net.jcdev.coolrss.model.entity.Tag;

/**
 *
 * @author carlos
 */
public class TagJpaController {

    public TagJpaController() {
        emf = Persistence.createEntityManagerFactory("CoolRSSPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Tag tag) throws PreexistingEntityException, Exception {
        if (tag.getFeedList() == null) {
            tag.setFeedList(new ArrayList<Feed>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Feed> attachedFeedList = new ArrayList<Feed>();
            for (Feed feedListFeedToAttach : tag.getFeedList()) {
                feedListFeedToAttach = em.getReference(feedListFeedToAttach.getClass(), feedListFeedToAttach.getFeedLink());
                attachedFeedList.add(feedListFeedToAttach);
            }
            tag.setFeedList(attachedFeedList);
            em.persist(tag);
            for (Feed feedListFeed : tag.getFeedList()) {
                Tag oldTagNameOfFeedListFeed = feedListFeed.getTagName();
                feedListFeed.setTagName(tag);
                feedListFeed = em.merge(feedListFeed);
                if (oldTagNameOfFeedListFeed != null) {
                    oldTagNameOfFeedListFeed.getFeedList().remove(feedListFeed);
                    oldTagNameOfFeedListFeed = em.merge(oldTagNameOfFeedListFeed);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findTag(tag.getTagName()) != null) {
                throw new PreexistingEntityException("Tag " + tag + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Tag tag) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Tag persistentTag = em.find(Tag.class, tag.getTagName());
            List<Feed> feedListOld = persistentTag.getFeedList();
            List<Feed> feedListNew = tag.getFeedList();
            List<String> illegalOrphanMessages = null;
            for (Feed feedListOldFeed : feedListOld) {
                if (!feedListNew.contains(feedListOldFeed)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Feed " + feedListOldFeed + " since its tagName field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Feed> attachedFeedListNew = new ArrayList<Feed>();
            for (Feed feedListNewFeedToAttach : feedListNew) {
                feedListNewFeedToAttach = em.getReference(feedListNewFeedToAttach.getClass(), feedListNewFeedToAttach.getFeedLink());
                attachedFeedListNew.add(feedListNewFeedToAttach);
            }
            feedListNew = attachedFeedListNew;
            tag.setFeedList(feedListNew);
            tag = em.merge(tag);
            for (Feed feedListNewFeed : feedListNew) {
                if (!feedListOld.contains(feedListNewFeed)) {
                    Tag oldTagNameOfFeedListNewFeed = feedListNewFeed.getTagName();
                    feedListNewFeed.setTagName(tag);
                    feedListNewFeed = em.merge(feedListNewFeed);
                    if (oldTagNameOfFeedListNewFeed != null && !oldTagNameOfFeedListNewFeed.equals(tag)) {
                        oldTagNameOfFeedListNewFeed.getFeedList().remove(feedListNewFeed);
                        oldTagNameOfFeedListNewFeed = em.merge(oldTagNameOfFeedListNewFeed);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = tag.getTagName();
                if (findTag(id) == null) {
                    throw new NonexistentEntityException("The tag with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Tag tag;
            try {
                tag = em.getReference(Tag.class, id);
                tag.getTagName();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The tag with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Feed> feedListOrphanCheck = tag.getFeedList();
            for (Feed feedListOrphanCheckFeed : feedListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Tag (" + tag + ") cannot be destroyed since the Feed " + feedListOrphanCheckFeed + " in its feedList field has a non-nullable tagName field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(tag);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Tag> findTagEntities() {
        return findTagEntities(true, -1, -1);
    }

    public List<Tag> findTagEntities(int maxResults, int firstResult) {
        return findTagEntities(false, maxResults, firstResult);
    }

    private List<Tag> findTagEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Tag.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Tag findTag(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Tag.class, id);
        } finally {
            em.close();
        }
    }

    public int getTagCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Tag> rt = cq.from(Tag.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
